<template>
	<view class="" style="height: 100vh;">
		<headerSlotVue :propsColor="'#fff'">
			<template v-slot:header>
				<view class="header_slot flex justify-start align-center" @click="closePage()">
					<view class="action" style="margin-right: 20rpx;">
						<text class="cuIcon-back "></text>
					</view>
					<view class="content text-bold">
						{{title}}
					</view>
				</view>
			</template>
		</headerSlotVue>
		<view class="page">
			<scroll-view class="scroll-view" scroll-y scroll-with-animation :scroll-top="top"
				:style="{height:viewHeight + 'px'}">
				<view style="padding: 30rpx 30rpx 80px;">
					<view class="message" :class="[item.userType]" v-for="(item,index) in list" :key="index">
						<image :src="item.avatar" v-if="item.userType === 'friend'" class="avatar" mode="widthFix">
						</image>
						<view class="content" v-if="item.msgType === 'image'">
							<image :src="item.content" @click="previewImage(item.content)" mode="widthFix"></image>
						</view>
						<view class="content" v-else>
							{{ item.content }}
						</view>
						<image :src="item.avatar" v-if="item.userType === 'self'" class="avatar" mode="widthFix">
						</image>
					</view>
				</view>
			</scroll-view>

			<view class="cu-bar input tool" :style="{bottom:changeBottomVal + 'px'}">


				<input v-model="content" @confirm="send" @focus="inputBindFocus" @blur="inputBindBlur"
					:adjust-position="false" class="solid-bottom input" maxlength="300" cursor-spacing="10" />
				<view class="action" @click="chooseImage">
					<text class="cuIcon-roundaddfill text-grey"></text>
				</view>
				<button class="cu-btn bg-green shadow-blur" @click="send">发送</button>
			</view>
			<!-- <view class="tool">
				<input type="text" v-model="content" class="input" @confirm="send" />
				<image src="/static/photo.png" mode="widthFix" class="thumb" @click="chooseImage"></image>
			</view> -->
		</view>
	</view>
</template>

<script>
	import headerSlotVue from '@/components/header-slot.vue';
	import storage from '@/utils/storage';
	import config from '@/config/config';
	import pageActivityManager from '@/utils/pageActivityManager.js';
	import {
		historyList,
		sendChat
	} from "@/api/chat.js"
	import {
		mapState
	} from 'vuex'
	export default {
		components: {
			headerSlotVue,
		},
		data() {
			return {
				config: '',
				userId: '', //当前聊天对象用户id
				title: '',
				content: '',
				list: [],
				top: 0,
				changeBottomVal: '',
				userInfo: {},
				refreshTimer: null, // 定时刷新消息的定时器
				isPageActive: true // 页面是否活跃
			};
		},
		onLoad(options) {
			this.title = options.name
			this._friendAvatar = options.avatar
			this.userId = options.userId
			this.userInfo = storage.getUserInfo()
			
			// 生成页面唯一ID
			this.pageId = `messageInfo_${this.userId}_${Date.now()}`;
			
			// 注册页面活跃状态
			pageActivityManager.registerPage(this.pageId, this);
			
			if (this.userId) {
				this.initHistoryList()
			}
		},
		onShow() {
			// 页面显示时设置为活跃状态
			pageActivityManager.registerPage(this.pageId, this);
			this.isPageActive = true;
			
			if (this.userId) {
				this.initHistoryList()
			}
			// 启动定时刷新
			this.startRefreshTimer()
		},
		onHide() {
			// 页面隐藏时设置为非活跃状态
			pageActivityManager.setPageInactive(this.pageId);
			this.isPageActive = false;
			this.clearRefreshTimer()
		},
		onUnload() {
			// 页面卸载时注销页面并清除定时器
			pageActivityManager.unregisterPage(this.pageId);
			this.isPageActive = false;
			this.clearRefreshTimer()
		},
		computed: {
			//计算聊天区域高度
			viewHeight() {
				//获取手机状态栏高度
				let statusBarHeight = uni.getSystemInfoSync()['statusBarHeight'];
				// #ifdef MP-WEIXIN
				// 获取微信胶囊的位置信息 width,height,top,right,left,bottom
				const custom = wx.getMenuButtonBoundingClientRect()

				// 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
				let navBarHeight = custom.height + (custom.top - statusBarHeight) * 2

				// #endif
				const systemInfo = uni.getSystemInfoSync();
				let viewHeightNum = systemInfo.windowHeight - (statusBarHeight + navBarHeight) - 70
				return viewHeightNum
			},
			...mapState(['chatUnreadCount', 'chatId'])
		},
		watch: {
			chatUnreadCount: {
				handler(newValue, oldValue) {
					if (this.userId === this.chatId) {
						this.initHistoryList()
					}
				},
			},
			chatId: {
				handler(newValue, oldValue) {
					// 当收到新消息时，如果当前聊天页面是消息发送者，则刷新消息列表
					if (newValue === this.userId) {
						this.initHistoryList()
					}
				},
				immediate: true
			}
		},
		methods: {
			//获取聊天记录
			initHistoryList() {
				historyList(this.userId).then(res => {
					res.data.data.forEach(item => {
						if (item.from._id === this.userInfo._id) {
							item.userType = 'self'
							item.avatar = item.from.avatar
						} else {
							item.userType = 'friend'
							item.avatar = item.from.avatar
						}
					})
					this.list = res.data.data
					this.scrollToBottom()
				})
			},
			closePage() {
				uni.navigateBack()
			},
			previewImage(imgUrl) {
				let imgArr = []
				this.list.filter(img => img.msgType === 'image').forEach(item => {
					imgArr.push(item.content)
				})
				uni.previewImage({
					current: imgUrl, // 当前显示图片的索引，这里始终是 0，因为只有一张图片
					urls: imgArr // 需要预览的图片链接列表
				});
			},
			inputBindFocus(e) {
				this.changeBottomVal = e.detail.height
			},
			inputBindBlur() {
				this.changeBottomVal = 0
			},
			send() {

				sendChat({
					to: this.userId,
					content: this.content
				}).then(res => {
					if (res.data.code === 200) {
						this.list.push({
							content: this.content,
							userType: 'self',
							avatar: this.userInfo.avatar,
							msgType: 'text',
							from: {
								_id: this.userInfo._id,
								avatar: this.userInfo.avatar
							}
						})

						this.content = ''
						this.scrollToBottom()
					}
				})

				// 模拟对方回复
				// setTimeout(() => {
				// 	this.list.push({
				// 		content: '周末什么安排',
				// 		userType: 'friend',
				// 		avatar: this.userInfo.avatar
				// 	})
				// 	this.scrollToBottom()
				// }, 1500)
			},
			chooseImage() {
				let self = this
				uni.chooseImage({
					count: 1, //最多可以选择的图片张数，默认9
					sizeType: ['compressed'], //original 原图，compressed 压缩图，默认二者都有 
					// sourceType: 'album',
					success: (res) => {
						const token = storage.getAccessToken()
						var imageSrc = res.tempFilePaths[0] //将图片的地址赋值给imageSrc
						uni.uploadFile({
							url: `${config.commonApi}/api/upload/wechat-image`,
							filePath: imageSrc,
							name: 'file',
							header: {
								'authorization': token
							},
							success(uploadFileRes) {

								let data = JSON.parse(uploadFileRes.data)
								self.list.push({
									content: data.data.url,
									userType: 'self',
									msgType: 'image',
									avatar: self.userInfo.avatar,
									from: {
										_id: self.userInfo._id,
										avatar: self.userInfo.avatar
									}
								})
								sendChat({
									to: self.userId,
									content: data.data.url,
									msgType: 'image'
								}).then(res => {
									if (res.data.code === 200) {
										self.scrollToBottom()
									}
								})
							},
							fail: (err) => { //接口调用失败的回调函数	
								console.log('失败返回：', err);
								uni.showModal({ //消息提示框
									content: err.errMsg, //错误信息
									showCancel: false
								});
							}
						})
					}
				})
			},
			scrollToBottom() {
				this.top = this.list.length * 1000
			},
			// 启动定时刷新
			startRefreshTimer() {
				this.clearRefreshTimer() // 先清除之前的定时器
				
				// 使用页面活跃状态管理工具创建定时器
				pageActivityManager.createPageTimer(
					this.pageId,
					'refreshMessages',
					() => {
						console.log('定时刷新聊天记录');
						this.initHistoryList();
					},
					5000, // 每5秒刷新一次
					() => this.userId && this.isPageActive // 执行条件
				);
			},
			// 清除定时刷新
			clearRefreshTimer() {
				pageActivityManager.clearPageTimer(this.pageId, 'refreshMessages');
			}
		}
	}
</script>

<style lang="scss" scoped>
	.header_slot {
		padding: 0 32rpx;
		width: 100%;
		font-weight: 500;
		font-size: 36rpx;
		color: #2C2622;
	}

	.scroll-view {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		box-sizing: border-box;
	}

	.message {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 10rpx;
			margin-right: 30rpx;
		}

		.content {
			min-height: 80rpx;
			max-width: 60vw;
			box-sizing: border-box;
			font-size: 28rpx;
			line-height: 1.3;
			padding: 20rpx;
			border-radius: 10rpx;
			background: #fff;

			image {
				width: 200rpx;
			}
		}

		&.self {
			justify-content: flex-end;

			.avatar {
				margin: 0 0 0 30rpx;
			}

			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-left: 16rpx solid #fff;
					right: -28rpx;
					top: 24rpx;
				}
			}
		}

		&.friend {
			.content {
				position: relative;

				&::after {
					position: absolute;
					content: '';
					width: 0;
					height: 0;
					border: 16rpx solid transparent;
					border-right: 16rpx solid #fff;
					left: -28rpx;
					top: 24rpx;
				}
			}
		}
	}

	.tool {
		position: absolute;
		width: 100%;
		min-height: 120rpx;
		left: 0;
		bottom: 0;
		background: #fff;
		display: flex;
		box-sizing: border-box;
		padding: 20rpx 24rpx 20rpx 40rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)/2) !important;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom)/2) !important;

		.input {
			background: #eee;
			border-radius: 10rpx;
			height: 70rpx;
			margin-right: 30rpx;
			flex: 1;
			padding: 0 20rpx;
			box-sizing: border-box;
			font-size: 28rpx;
		}

		.thumb {
			width: 64rpx;
		}
	}
</style>